//
//  SearchViewController.m
//  MyProject
//
//  Created by 石小强 on 2018/3/21.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "SearchViewController.h"
#import "NSUDManager.h"
#import "SearchPreCell.h"
#import "SearchNavView.h"
#import "SearchResultView.h"

#import "EntryProtectDetailVC.h"
#import "CompanyMainViewController.h"
#import "JobDetailVC.h"
#import "WorkmateMainVC.h"
#import "HelpDetailVC.h"

@interface SearchViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) SearchNavView *searchNavView;
@property (nonatomic, strong) UITableView *searchPreTableView;
@property (nonatomic, strong) SearchResultView *searchResultView;

//历史记录数据数组
@property(nonatomic, strong) NSArray<NSString*> *historyList;
@property(nonatomic, strong) NSMutableArray<NSAttributedString*> *hotSearchList;

//当前显示数据的类型
@property(atomic, assign) NSInteger displayType; //0 历史记录  1 热词列表

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航栏
    [self setupNavBar];
    
    // 加载子页面
    [self addSubViews];
    
    // 获取历史数据
    [self fetchSearchHistoryDataList];
    
    [_searchNavView.searchTF performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.5];
}


- (void)addSubViews {
    _searchPreTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - NAV_STATUS_H) style:UITableViewStylePlain];
    _searchPreTableView.tag = 0;
    [_searchPreTableView setBackgroundColor:UIColorFromRGB(0xF2F5FA)];
    _searchPreTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _searchPreTableView.delegate = self;
    _searchPreTableView.dataSource = self;
    [self.view addSubview:_searchPreTableView];
    [_searchPreTableView registerNib:[UINib nibWithNibName:@"SearchPreCell" bundle:nil] forCellReuseIdentifier:@"preCellID"];
    
    //搜索结果tableview
    _searchResultView = [[SearchResultView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-NAV_STATUS_H)];
    _searchResultView.hidden = YES;
    WS(weakSelf)
    _searchResultView.companyBlock = ^(CompanyModel *company) {
        CompanyMainViewController *vc = [[CompanyMainViewController alloc] init];
        vc.companyId = company.companyId;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    _searchResultView.positionBlock = ^(PositionModel *position) {
        JobDetailVC *vc = [[JobDetailVC alloc] init];
        vc.positionId = position.positionId;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    _searchResultView.workmateBlock = ^(WorkmateModel *workmate) {
        WorkmateMainVC *vc = [[WorkmateMainVC alloc] init];
        vc.userId = workmate.userId;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    _searchResultView.questionBlock = ^(QuestionModel *question) {
        HelpDetailVC *vc = [[HelpDetailVC alloc] init];
        vc.relatedId = question.questionId;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    _searchResultView.decryptBlock = ^(DecryptModel *decrypt) {
        EntryProtectDetailVC *vc = [[EntryProtectDetailVC alloc] init];
        vc.index = 1;
        vc.decryptId = decrypt.incumbentDecryptId;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    [self.view addSubview:_searchResultView];
}

/** 删除所有历史搜索提示 */
- (void)clearHistoryHappen {
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认删除历史搜索记录?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *actionComfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [NSUDManager synSetValue:nil forKey:kSearchHistoryList];
            self.historyList = [[NSArray alloc] init];
            [self.searchPreTableView reloadData];
        });
    }];
    
    [actionCancel setValue:UIColorFromRGB(0x1AA9BA) forKey:@"titleTextColor"];
    [actionComfirm setValue:UIColorFromRGB(0x1AA9BA) forKey:@"titleTextColor"];
    [alertC addAction:actionCancel];
    [alertC addAction:actionComfirm];
    [self presentViewController:alertC animated:YES completion:nil];
}

// 设置导航栏
- (void)setupNavBar {
    _searchNavView = [[SearchNavView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    [_searchNavView.cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _searchNavView.searchTF.delegate = self;
//    [_searchNavView.searchTF addTarget:self action:@selector(searchTextDidChange) forControlEvents:UIControlEventValueChanged];
    _searchNavView.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar addSubview:_searchNavView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _searchNavView.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _searchNavView.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
}

- (void)cancelBtnClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"textFieldShouldReturn");
    if (textField.text.length > 0) {
//        [CommonUtils showToast:@"请输入关键字"];
//        return NO;
        
        //搜索历史 本地记录
        NSMutableArray *searchList = [[NSMutableArray alloc] initWithArray:[NSUDManager getValueforKey:kSearchHistoryList]];
        NSMutableIndexSet *mutSet = [[NSMutableIndexSet alloc] init];
        for (int index = 0; index < [searchList count]; index++) {
            NSString *searchKey = searchList[index];
            if([searchKey isEqualToString:textField.text]){
                [mutSet addIndex:index];
            }
        }
        [searchList removeObjectsAtIndexes:mutSet];
        
        NSString *testStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        if([testStr length] > 0){
            [searchList insertObject:textField.text atIndex:0];
            [NSUDManager synSetValue:searchList forKey:kSearchHistoryList];
        }
    }
    
    // 请求数据
    self.searchResultView.key = textField.text;
    [self.searchResultView clearData];
    [self fetchDataSign];
    [textField resignFirstResponder];
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField { // 一获取焦点就走此方法
    NSLog(@"textFieldDidBeginEditing");
    NSString *nowText = textField.text;
    if ([nowText length] == 0) {
        [self fetchSearchHistoryDataList];
    } else {
//        [self fetchHotSearchKeyWordDataList:nowText];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"shouldChangeCharactersInRange");

    if (range.location == 0 && range.length == 1 && [string isEqualToString:@""]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            _searchResultView.hidden = YES;
            _searchPreTableView.hidden = NO;
        });
        [self fetchSearchHistoryDataList];
    }
    
    return YES;
}


- (void)fetchDataSign {
    dispatch_async(dispatch_get_main_queue(), ^{
        _searchResultView.hidden = NO;
        _searchPreTableView.hidden = YES;
    });
    
    _searchResultView.key = _searchNavView.searchTF.text;
    [_searchResultView loadComprehensiveData];
    [_searchResultView setSelectIndex:0];
}

- (void)fetchSearchHistoryDataList {
    self.displayType = 0;
    self.historyList = [NSUDManager getValueforKey:kSearchHistoryList];
    if (self.historyList.count > 5) {
        self.historyList = [self.historyList subarrayWithRange:NSMakeRange(0, 5)];
    }
    [self searchHistoryListRefreshUISign];
}

- (void)searchHistoryListRefreshUISign {
    dispatch_async(dispatch_get_main_queue(), ^{
        _searchResultView.hidden = YES;
        _searchPreTableView.hidden = NO;
        [_searchPreTableView reloadData];
    });
}

- (void)fetchHotSearchKeyWordDataList:(NSString *)searchText {
    self.displayType = 1;
#warning 请求接口
}

- (void)hotSearchKeyWordListRefreshUISign {
    
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 0) {
        if (self.displayType == 0) {
            return self.historyList.count;
        } else {
            return self.hotSearchList.count;
        }
    } else {
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 0) {
        return 43;
    } else {
        return 100;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 0 && self.displayType == 0) {
        return 43;
    } else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView.tag == 0 && self.displayType == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 43)];
        [view setBackgroundColor:kStyleColor];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 43)];
        label.textColor = UIColorFromRGB(0x96ABB5);
        label.font = k12Font;
        label.text = @"搜索历史";
        [view addSubview:label];
        UIButton *delete = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 44, 0, 44, 43)];
        [delete setImage:[UIImage imageNamed:@"iconfont-delete"] forState:UIControlStateNormal];  // 14*14
        [delete addTarget:self action:@selector(clearHistoryHappen) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:delete];
        return view;
    } else {
        UIView *view = [[UIView alloc] init];
        return view;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 0) {
        SearchPreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"preCellID"];
        if (self.displayType == 0) {
            [cell.nameL setText:[self.historyList objectAtIndex:indexPath.row]];
            cell.deleteB.hidden = NO;
            cell.deleteBlock = ^(NSString *str) {
                NSMutableArray *searchList = [[NSMutableArray alloc] initWithArray:[NSUDManager getValueforKey:kSearchHistoryList]];
                NSMutableIndexSet *mutSet = [[NSMutableIndexSet alloc] init];
                for (int index = 0; index < [searchList count]; index++) {
                    NSString *searchKey = searchList[index];
                    if([searchKey isEqualToString:str]){
                        [mutSet addIndex:index];
                    }
                }
                [searchList removeObjectsAtIndexes:mutSet];
                [NSUDManager synSetValue:searchList forKey:kSearchHistoryList];
                self.historyList = searchList;
                [self.searchPreTableView reloadData];
            };
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else {
            [cell.nameL setAttributedText:[self.hotSearchList objectAtIndex:indexPath.row]];
            cell.deleteB.hidden = YES;
            return cell;
        }
        
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"goods"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"goods"];
        }
        cell.textLabel.text = [NSString stringWithFormat:@"indexPath.row=%zd", indexPath.row];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"点击了---indexPath = %zd", indexPath.row);
    if (tableView.tag == 0 && self.displayType == 0) {
//        [cell.nameL setText:[self.historyList objectAtIndex:indexPath.row]];
        
        self.searchNavView.searchTF.text = [self.historyList objectAtIndex:indexPath.row];
        [self.searchNavView.searchTF resignFirstResponder];
        self.searchResultView.key = [self.historyList objectAtIndex:indexPath.row];
        [self.searchResultView clearData];
        [self fetchDataSign];
    }
}

@end
